﻿using System;
using System.Globalization;
using Monkey.Warrenty.Biz;
using Monkey.Warrenty.Constants;
using Monkey.Warrenty.EntityModel;
using Monkey.Warrenty.Enum;
using MonkeyWarranty.Web.Common;

namespace MonkeyWarranty.Web.InstantTickets
{
    public partial class EditProduct : System.Web.UI.Page
    {
        #region Properties

        private InstantTicket_Product _ticketProduct;
        private InstantTicket_Product TicketProduct
        {
            get
            {
                if (_ticketProduct == null)
                {
                    if (TicketProductId > 0)
                    {
                        _ticketProduct = InstantTicketManager.GetTicketProductById(TicketProductId);
                    }
                }
                return _ticketProduct;
            }
        }

        private static CustomerBiz _customerBiz;
        private static CustomerBiz CustomerManager
        {
            get { return _customerBiz ?? (_customerBiz = new CustomerBiz()); }
        }

        private static EmployeeBiz _employeeBiz;

        private static EmployeeBiz EmployeeManager
        {
            get { return _employeeBiz ?? (_employeeBiz = new EmployeeBiz()); }
        }

        protected long TicketId
        {
            get { return (TicketProduct != null) ? TicketProduct.InstantTicketId : 0; }
        }

        private Product _product;
        protected Product CurrentProduct
        {
            get
            {
                if (_product == null)
                {
                    if (TicketProduct != null)
                    {
                        _product = ProductManager.GetById(TicketProduct.ProductId);
                    }
                }
                return _product;
            }
        }

        private long _ticketProductId;
        private long TicketProductId
        {
            get
            {
                if (_ticketProductId <= 0) long.TryParse(Request.Params["id"], out _ticketProductId);
                return _ticketProductId;
            }
        }

        private static ProductBiz _productBiz;
        private static ProductBiz ProductManager
        {
            get { return _productBiz ?? (_productBiz = new ProductBiz()); }
        }

        private static InstantTicketBiz _instantTicketBiz;
        private static InstantTicketBiz InstantTicketManager
        {
            get { return _instantTicketBiz ?? (_instantTicketBiz = new InstantTicketBiz()); }
        }

        private static CategoryBiz _categoryBiz;
        private static CategoryBiz CategoryManager
        {
            get { return _categoryBiz ?? (_categoryBiz = new CategoryBiz()); }
        }

        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            if (WarrantyCommon.CurrrentEmployee == null)
            {
                Response.Redirect("~/Logon.aspx");
                return;
            }

            if (!WarrantyCommon.CurrrentEmployee.HasRole(RoleConstant.AdminDichVu))
            {
                Response.Redirect("~/NoPermission.aspx");
            }

            if (!IsPostBack)
            {
                if (TicketProductId <= 0 || TicketProduct == null)
                {
                    errorMessage.Visible = true;
                    lblErrorMessage.Text = Resources.GlobalStrings.ProductNotExisted;
                    btnSave.Enabled = false;
                    return;
                }

                LoadData();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            errorMessage.Visible = false;
            lblErrorMessage.Text = string.Empty;

            // validate inputs
            var productId = hidProductId.Value;
            if (string.IsNullOrEmpty(productId))
            {
                errorMessage.Visible = true;
                lblErrorMessage.Text = Resources.GlobalStrings.ProductIsRequired;
                return;
            }
            var descrition = txtDescription.Text;
            var model = txtModel.Text.Trim();
            var serial = txtSerial.Text.Trim();
            var note = txtNote.Text;

            TicketProduct.ProductId = int.Parse(productId);
            TicketProduct.Description = descrition;
            TicketProduct.Model = model;
            TicketProduct.Serial = serial;
            TicketProduct.Note = note;

            int quantity;
            if (int.TryParse(txtQuantity.Text.Trim(), out quantity)) TicketProduct.Quantity = quantity;

            int manId;
            if (int.TryParse(ddlManufacturers1.SelectedValue, out manId)) TicketProduct.ManufacturerId = manId;

            int warrantyTypeId;
            if (int.TryParse(ddlWarrantyTypes.SelectedValue, out warrantyTypeId)) TicketProduct.WarrantyTypeId = warrantyTypeId;

            int errorId;
            if (int.TryParse(ddlErrors.SelectedValue, out errorId)) TicketProduct.ErrorId = errorId;

            DateTime warrantyDate;
            var strWarrantyDate = txtWarrantyDate.Text.Trim();
            if (DateTime.TryParseExact(strWarrantyDate.Split(' ')[0], "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out warrantyDate))
            {
                TicketProduct.WarrantyDate = warrantyDate;
            }

            double months;
            if (double.TryParse(txtMonths.Text.Trim(), out months) && months >= 0) TicketProduct.Months = months;

            int warrantyCount;
            if (int.TryParse(txtWarrantyCount.Text.Trim(), out warrantyCount)) TicketProduct.WarrantyCount = warrantyCount;

            int supplierId;
            if (int.TryParse(ddlSuppliers.SelectedValue, out supplierId)) TicketProduct.SupplierId = supplierId;

            int employeeId;
            if (int.TryParse(ddlEmployees.SelectedValue, out employeeId) && employeeId > 0)
            {
                TicketProduct.EmployeeId = employeeId;
            }
            else
            {
                TicketProduct.EmployeeId = null;
            }

            int statusId;
            if (int.TryParse(ddlInstantProductStatus.SelectedValue, out statusId))
            {
                TicketProduct.InstantProductStateId = statusId;
            }

            DateTime startDate;
            if (DateTime.TryParseExact(txtStartDate.Text.Trim(), "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out startDate))
            {
                TicketProduct.StartDate = startDate;
            }
            else
            {
                TicketProduct.StartDate = null;
            }

            DateTime endDate;
            if (DateTime.TryParseExact(txtEndDate.Text.Trim(), "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out endDate))
            {
                TicketProduct.EndDate = endDate;
            }
            else
            {
                TicketProduct.EndDate = null;
            }

            // Call Biz Save Product
            InstantTicketManager.UpdateTicketProduct(TicketProduct);

            errorMessage.Visible = true;
            lblErrorMessage.Text = Resources.GlobalStrings.UpdateSuccess;

            //Response.Redirect("Edit.aspx?id=" + TicketProduct.InstantTicketId);
        }

        #endregion

        #region Helpers

        private void LoadData()
        {
            // instant ticket
            var ticket = InstantTicketManager.GetById(TicketId);
            if (ticket == null)
            {
                return;
            }
            ltrTicketCode.Text = ticket.Code;
            ltrContent.Text = ticket.TicketContent;
            ltrDistance.Text = string.Format("{0:0.00}", ticket.Distance);
            ltrReceivedDate.Text = string.Format("{0:dd/MM/yyyy HH:mm}", ticket.CreatedDate);
            ltrDescription.Text = string.IsNullOrEmpty(ticket.Description) ? string.Empty : ticket.Description.Replace("\n", "<br />");

            // customer
            var customer = CustomerManager.GetById(ticket.CustomerId);
            if (customer != null)
            {
                ltrCustomerName.Text = customer.Name;
                ltrCustomerAddress.Text = customer.Address;
                ltrCustomerPhone.Text = customer.Phone;
                ltrCustomerEmail.Text = customer.Email;
            }

            // ticket product
            hidProductId.Value = TicketProduct.ProductId.ToString(CultureInfo.InvariantCulture);
            if (CurrentProduct != null)
            {
                txtCode.Text = CurrentProduct.Code;
                txtName.Text = CurrentProduct.Name;
            }
            txtModel.Text = TicketProduct.Model;
            txtSerial.Text = TicketProduct.Serial;
            txtQuantity.Text = TicketProduct.Quantity.ToString(CultureInfo.InvariantCulture);
            txtDescription.Text = TicketProduct.Description;
            txtWarrantyDate.Text = string.Format("{0:dd/MM/yyyy HH:mm}", TicketProduct.WarrantyDate);
            txtMonths.Text = string.Format("{0:0.0}", TicketProduct.Months);
            txtWarrantyCount.Text = string.Format("{0}", TicketProduct.WarrantyCount);
            txtNote.Text = TicketProduct.Note;

            if (TicketProduct.StartDate.HasValue)
            {
                txtStartDate.Text = string.Format("{0:dd/MM/yyyy HH:mm}", TicketProduct.StartDate);
            }
            if (TicketProduct.EndDate.HasValue)
            {
                txtEndDate.Text = string.Format("{0:dd/MM/yyyy HH:mm}", TicketProduct.EndDate);
            }

            // product groups
            var groups = ProductManager.GetAllProductGroups();
            groups.Insert(0, new ProductGroup { Id = 0, Name = Resources.GlobalStrings.AllGroups });
            ddlProductGroups.DataTextField = "Name";
            ddlProductGroups.DataValueField = "Id";
            ddlProductGroups.DataSource = groups;
            ddlProductGroups.DataBind();

            // mans product
            var manufacturers = ProductManager.GetAllManufacturers();
            manufacturers.Insert(0, new Manufacturer { Id = 0, Name = Resources.GlobalStrings.AllManufacturers });
            ddlManufacturers.DataTextField = "Name";
            ddlManufacturers.DataValueField = "Id";
            ddlManufacturers.DataSource = manufacturers;
            ddlManufacturers.DataBind();

            // mans ticket
            manufacturers[0].Name = string.Empty;
            ddlManufacturers1.DataTextField = "Name";
            ddlManufacturers1.DataValueField = "Id";
            ddlManufacturers1.DataSource = manufacturers;
            ddlManufacturers1.DataBind();
            ddlManufacturers1.SelectedValue = string.Format("{0}", TicketProduct.ManufacturerId);

            // warranty types
            var warrantyTypes = CategoryManager.GetAllWarrantyTypes();
            warrantyTypes.Insert(0, new WarrantyType { Id = 0, Name = string.Empty });
            ddlWarrantyTypes.DataTextField = "Name";
            ddlWarrantyTypes.DataValueField = "Id";
            ddlWarrantyTypes.DataSource = warrantyTypes;
            ddlWarrantyTypes.DataBind();
            ddlWarrantyTypes.SelectedValue = string.Format("{0}", TicketProduct.WarrantyTypeId);

            // errors
            var errors = ProductManager.GetAllErrors();
            errors.Insert(0, new Error { Id = 0, Name = string.Empty });
            ddlErrors.DataTextField = "DisplayName";
            ddlErrors.DataValueField = "Id";
            ddlErrors.DataSource = errors;
            ddlErrors.DataBind();
            ddlErrors.SelectedValue = string.Format("{0}", TicketProduct.ErrorId);

            // suppliers
            var suppliers = ProductManager.GetAllSuppliers();
            suppliers.Insert(0, new Supplier { Id = 0, Name = string.Empty });
            ddlSuppliers.DataTextField = "Name";
            ddlSuppliers.DataValueField = "Id";
            ddlSuppliers.DataSource = suppliers;
            ddlSuppliers.DataBind();
            ddlSuppliers.SelectedValue = string.Format("{0}", TicketProduct.SupplierId);

            // technical employees
            var employees = EmployeeManager.GetEmployeesOfRole((int)UserRole.KythuatDichVu);
            employees.Insert(0, new Employee { Id = 0, Name = string.Empty });
            ddlEmployees.DataSource = employees;
            ddlEmployees.DataValueField = "Id";
            ddlEmployees.DataTextField = "Name";
            ddlEmployees.DataBind();
            ddlEmployees.SelectedValue = string.Format("{0}", TicketProduct.EmployeeId ?? 0);

            // status
            ddlInstantProductStatus.SelectedValue = string.Format("{0}", TicketProduct.InstantProductStateId);
        }

        #endregion
    }
}